﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Net;

public partial class Stats : System.Web.UI.Page
{
    List<string> teamNames;
    List<Player> players, lineup;
    User user;
    JsonParser jsonParser;


    protected void Page_Init(object sender, EventArgs e)
    {
        addTeamsToDropdown();
        addPositionsToDropdown();
        teamNames = new List<string>();
        user = (User)Session["UserSession"];
        lineup = new List<Player>();
        jsonParser = new JsonParser();
        GameweekTeam currentTeam = jsonParser.getTeam("1", User.Identity.Name);

        foreach (Player player in currentTeam.keepers)
        {
            lineup.Add(player);
        }
        foreach (Player player in currentTeam.defenders)
        {
            lineup.Add(player);
        }
        foreach (Player player in currentTeam.midfielders)
        {
            lineup.Add(player);
        }
        foreach (Player player in currentTeam.forwards)
        {
            lineup.Add(player);
        }
        addPlayersToDropdown();
          

        try
        {
            if (user != null)
            {
                players = jsonParser.getAvailablePlayers(user.username);
                initPlayers(players);
                list(players);
            }                      
        }
        catch (NullReferenceException ex)
        {
            Response.Redirect("~/Account/NewTeam.aspx");
        }
        catch (WebException ex)
        {
            Response.Redirect("~/Account/NewTeam.aspx");
        }
    }


    protected void transferButton_Click(Object sender, EventArgs e)
    {

        int inPlayerId = (int)Session["selectedPlayer"];
        int outPlayerId = lineup.ElementAt(PlayersDD.SelectedIndex).playerID;

        if (user != null)
        {
            jsonParser.transferPlayer(user.username, user.password, inPlayerId.ToString(), outPlayerId.ToString());
        }
    }


    protected void onTeam_Selected(object sender, EventArgs e)
    {
        string selectedTeam = ((DropDownList)sender).SelectedValue.ToString();
        string selectedPos = PositionDD.SelectedValue.ToString();
        PlayerPanel.Controls.Clear();
        if (!selectedTeam.Equals("all"))
        {
            if (selectedPos.Equals("all"))
            {
                Team team = (Team)Enum.Parse(typeof(Team), selectedTeam, true);
                list(players, team);
            }
            else
            {
                Team team = (Team)Enum.Parse(typeof(Team), selectedTeam, true);
                Position position = (Position)Enum.Parse(typeof(Position), selectedPos, true);
                list(players, team, position);
            }
        }
        else
        {

            if (selectedPos.Equals("all"))
            {

                list(players);
            }
            else
            {
                Position position = (Position)Enum.Parse(typeof(Position), selectedPos, true);
                list(players, position);
            }
        }
    }

    protected void onPosition_Selected(object sender, EventArgs e)
    {
        string selectedPos = ((DropDownList)sender).SelectedValue.ToString();
        string selectedTeam = TeamDD.SelectedValue.ToString();
        PlayerPanel.Controls.Clear();
        if (!selectedPos.Equals("all"))
        {
            if (selectedTeam.Equals("all"))
            {
                Position pos = (Position)Enum.Parse(typeof(Position), selectedPos, true);
                list(players, pos);
            }
            else
            {
                Team team = (Team)Enum.Parse(typeof(Team), selectedTeam, true);
                Position position = (Position)Enum.Parse(typeof(Position), selectedPos, true);
                list(players, team, position);
            }
        }
        else
        {
            if (selectedTeam.Equals("all"))
            {
                list(players);
            }
            else
            {
                Team team = (Team)Enum.Parse(typeof(Team), selectedTeam, true);
                list(players, team);
            }
        }
    }

    private void initPlayers(List<Player> players)
    {
        foreach (Player player in players)
        {
            player.setRealTeam();
        }
    }

    private void list(List<Player> players)
    {
        if (players != null)
        {
            foreach (Player player in players)
            {
                addPlayerControls(player);
            }
            PlayerPanel.Controls.Add(new LiteralControl("<br />"));
        }
    }

    private void list(List<Player> players, Position position)
    {
        if (players != null)
        {
            foreach (Player player in players)
            {
                if (player.position.Equals(position))
                {
                    addPlayerControls(player);
                }
            }
            PlayerPanel.Controls.Add(new LiteralControl("<br />"));
        }
    }

    private void list(List<Player> players, Team team)
    {
        if (players != null)
        {

            foreach (Player player in players)
            {
                if (player.team.Equals(team))
                {
                    addPlayerControls(player);
                }
            }
            PlayerPanel.Controls.Add(new LiteralControl("<br />"));
        }
    }

    private void addPlayersToDropdown()
    {
        for (int i = 0; i < lineup.Count; i++)
        {
            PlayersDD.Items.Add(new ListItem(lineup.ElementAt(i).playerName));
            PlayersDD.DataBind();
        }
    }

    private void addPlayerControls(Player player)
    {
        LinkButton playerClickable = new LinkButton();
        playerClickable.Text = player.playerName;
        playerClickable.Command += new CommandEventHandler(this.PickPlayer);
        playerClickable.ID = "playerClick_" + player.playerID.ToString();
        playerClickable.CommandArgument = player.playerID.ToString();
        PlayerPanel.Controls.Add(playerClickable);
        PlayerPanel.Controls.Add(new LiteralControl("<br />"));
    }

    void PickPlayer(Object sender, CommandEventArgs e)
    {
        Debug.WriteLine("PlayerID: " + e.CommandArgument);
        jsonParser.pickPlayer(user.username, user.password, e.CommandArgument.ToString());
        Session["selectedPlayer"] = int.Parse(e.CommandArgument.ToString());
        Debug.WriteLine(Session["selectedPlayer"]);

    }

    private void list(List<Player> players, Team team, Position position)
    {
        if (players != null)
        {
            foreach (Player player in players)
            {
                if (player.team.Equals(team) && player.position.Equals(position))
                {
                    addPlayerControls(player);
                }
            }
            PlayerPanel.Controls.Add(new LiteralControl("<br />"));
        }
    }

    private void addTeamsToDropdown()
    {
        Array itemValues = System.Enum.GetValues(typeof(Team));
        Array itemNames = System.Enum.GetNames(typeof(Team));

        ListItem item2 = new ListItem("All teams", "all");
        TeamDD.Items.Add(item2);

        for (int i = 0; i <= itemNames.Length - 1 ; i++) {
            ListItem item = new ListItem(removeUnderscore(itemNames.GetValue(i).ToString()), itemValues.GetValue(i).ToString());
            TeamDD.Items.Add(item);
        }
    }

    private void addPositionsToDropdown()
    {
        Array itemValues = System.Enum.GetValues(typeof(Position));
        Array itemNames = System.Enum.GetNames(typeof(Position));

        ListItem item2 = new ListItem("All players", "all");
        PositionDD.Items.Add(item2);

        for (int i = 0; i <= itemNames.Length - 1; i++)
        {
            ListItem item = new ListItem(removeUnderscore(itemNames.GetValue(i).ToString()), itemValues.GetValue(i).ToString());
            PositionDD.Items.Add(item);
        }
    }

    private string removeUnderscore(string st)
    {
        st = st.Replace('_', ' ');
        return st;
    }
}
